/* ECE454 Project 1: client.c  */
/* Acknowledgement: The socket part was implemented with the help of http://www.linuxhowtos.org/C_C++/socket.htm  */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <netdb.h>
#include <fcntl.h>
#include "./Peers.h"

#define FILEPATH "../peer.c"

void error( const char * msg ) 
{
	perror(msg);
	exit(0);
}

int main( int argc, char * argv[] )
{
	int cliSocket, portNo, n;
	struct sockaddr_in srvr_addr;
	struct hostent * server;
	char buffer[256];
	FILE * fp;
	char * file;
	Peer p;	
	
	file = (char *) malloc(1000*sizeof(char));	

	if( argc < 3 ) {
		fprintf(stderr, "usage %s hostname port \n", argv[0] );
		exit(0);
	}
	
	portNo = atoi(argv[2]);
	
	cliSocket = socket(AF_INET, SOCK_STREAM, 0);

	if( cliSocket < 0 )
		error("Error! in opening socket");

	server = gethostbyname(argv[1]);
	
	if( server == NULL) {
		fprintf(stderr, "Error! no such host \n");
		exit(0);
	} 

	bzero( (char *) &srvr_addr, sizeof(srvr_addr) );
	srvr_addr.sin_family = AF_INET;

	bcopy( (char *) server->h_addr, (char *) &srvr_addr.sin_addr.s_addr, server->h_length );

	srvr_addr.sin_port = htons(portNo);

	if( connect( cliSocket, (struct sockaddr *) &srvr_addr, sizeof(srvr_addr)) < 0 )
		error("Error! in connecting");

	printf("Name of the file?: ");
	bzero(buffer, 256);
	fgets(buffer, 255, stdin); // reading the string from terminal	

	n = write( cliSocket, buffer, 255 );

	if( n < 0 )
		error( "Error! in writing to the socket" );

	n = read(cliSocket, file, 255);
	if( n < 0 )
		error( "Error! in reading from the socket" );
	//printf("file data: %s\n", file);
		
	fp = fopen("./test.txt", "wb");
	fwrite(file, sizeof(char), 1000, fp);

	printf("The file is received successfully\n");
	close(cliSocket);
	
	return 0;	
}

